package com.example.tourpal.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.example.tourpal.MainActivity;
import com.example.tourpal.R;
import com.example.tourpal.model.User;
import com.example.tourpal.model.UserDataManager;
import com.example.tourpal.model.UserDataManager.UserDataLishenter;
import com.example.tourpal.util.SharePreferencesManager;
import com.example.tourpal.util.SimpleCrypto;
import com.example.tourpal.util.Tools;

public class LoginActivity extends Activity {
	private static final String TAG = "chengongguo/LoginActivity";
	private Tools mTools;
	private SharePreferencesManager mSharePreferencesManager;

	public static final int REQUEST_LOGIN = 100;
	public static final int RESULT_LOGIN = 101;
	private ImageView mBackTextView;
	private TextView mRegisterTextView;
	private EditText mAccountEditText;
	private EditText mPasswordEditText;
	private TextView mforgetTextView;
	private Button mLoginButton;
	// private CheckBox mLoginPasswordRemember;
	private CheckBox mLoginAutoLogin;
	// private Boolean user_password_remember=true;
	private Boolean mAutoLogin = true;
	private String mAccount;
	private String mPassword;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_login_view);
		initCommonManager();
		initContentView();
	}

	private void initCommonManager() {
		// TODO Auto-generated method stub
		mTools = new Tools(this, TAG);
		mSharePreferencesManager = new SharePreferencesManager(this);
	}

	private void initContentView() {
		// TODO Auto-generated method stub
		mBackTextView = (ImageView) findViewById(R.id.back);
		mBackTextView.setOnClickListener(mListener);
		mAccountEditText = (EditText) findViewById(R.id.edittext_login_account);

		mPasswordEditText = (EditText) findViewById(R.id.edittext_login_password);
		// mLoginPasswordRemember = (CheckBox)
		// findViewById(R.id.checkbox_login_password_remember);
		// mLoginPasswordRemember
		// .setOnCheckedChangeListener(new OnCheckedChangeListener() {
		//
		// @Override
		// public void onCheckedChanged(CompoundButton arg0,
		// boolean isChecked) {
		// // TODO Auto-generated method stub
		// user_password_remember = isChecked;
		// }
		// });
		// if (user_password_remember) {
		// mLoginPasswordRemember.setChecked(true);
		// mLoginPassword.setText(user.getUserPwd());
		// }

		mLoginAutoLogin = (CheckBox) findViewById(R.id.checkbox_login_auto_login);
		mLoginAutoLogin
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean isChecked) {
						// TODO Auto-generated method stub
						mAutoLogin = isChecked;
					}
				});

		mLoginButton = (Button) findViewById(R.id.button_login);
		mLoginButton.setOnClickListener(mListener);

		mforgetTextView = (TextView) findViewById(R.id.textview_login_forget_password);
		mforgetTextView.setOnClickListener(mListener);

		mRegisterTextView = (TextView) findViewById(R.id.textview_user_title_register);
		mRegisterTextView.setVisibility(View.VISIBLE);
		mRegisterTextView.setOnClickListener(mListener);
	}

	OnClickListener mListener = new OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.textview_user_title_register:
				register();
				break;
			case R.id.button_login:
				login();
				break;
			case R.id.textview_login_forget_password:
				findPassword();
				break;
			case R.id.back:
				finish();
				break;
			}
		}
	};

	public void login() {
		if (isEditTextValid()) {
			// User user = new User(mAccount, null, null, 1, mPassword);
			User user = new User(1, mAccount, null, 1, mPassword);
			if (mAccount.equals("test")
					/*&& mPassword.equals("39FC42C96B8CE356EDF5A920835D0565")*/) {
				mSharePreferencesManager.writeUserInfo(mAutoLogin, mAccount,
						mPassword);
				mSharePreferencesManager
						.writeUserAccessToken("a0b58a26-dd7b-421e-840e-bff7f8d788a8");
				mSharePreferencesManager.writeUserId(1);
				mSharePreferencesManager.writeUserName("wuliqing");
				stratMainActivity(User.getDefaultUser());
				return;
			}
			UserDataManager userDataManager = new UserDataManager(this);
			userDataManager.login(user, new UserDataLishenter() {
				@Override
				public void requestUserData(User user) {
					mSharePreferencesManager.writeUserInfo(mAutoLogin,
							mAccount, mPassword);
					mSharePreferencesManager.writeUserAccessToken(user
							.getAccessToken());
					mSharePreferencesManager.writeUserId(user.getId());
					mSharePreferencesManager.writeUserName(user.getUserName());
					stratMainActivity(user);
				}
			});
		}
	}

	private void stratMainActivity(User user) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, MainActivity.class);
		Bundle userBundle = new Bundle();
		userBundle.putSerializable("user", user);
		intent.putExtras(userBundle);
		setResult(RESULT_LOGIN, intent);
		finish();
	}

	protected void findPassword() {
		Intent intent = new Intent(this, FindPasswordActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);
	}

	public void register() {
		Intent intent = new Intent(this, RegisterActivity.class);
		startActivityForResult(intent, RegisterActivity.REQUEST_REGISTER);
		overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);
	}

	public boolean isEditTextValid() {
		mAccount = mAccountEditText.getText().toString().trim();
		String password = mPasswordEditText.getText().toString().trim();
		try {
			mPassword = SimpleCrypto.encrypt(SimpleCrypto.SEED, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (mAccount.equals("")) {
			mTools.showToast(getString(R.string.user_account_empty));
			return false;
		} else if (mPassword.equals("")) {
			mTools.showToast(getString(R.string.user_pwd_empty));
			return false;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "onActivityResult()");
		if (data != null) {
			if (resultCode == RegisterActivity.RESULT_REGISTER) {
				setResult(RESULT_LOGIN, data);
				finish();
			}
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(R.anim.main_enter, R.anim.sub_exit);
	}
}